package com.hm.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hm.reggie.dto.DishDto;
import com.hm.reggie.entity.Dish;
import com.hm.reggie.entity.DishFlavor;
import com.hm.reggie.mapper.DishMapper;
import com.hm.reggie.service.DishFlavorService;
import com.hm.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;

    /***
     * 新增菜品同时保存口味
     * @param dishDto
     */
    //开启事务管理
    @Transactional
    public void saveWithFlavor(DishDto dishDto) {
        //保存到dish
        save(dishDto);
        //保存到dishflavor
        List<DishFlavor> dishFlavors = dishDto.getFlavors();
        //获取dish——id,写入每个dishflavor
        Long dishid = dishDto.getId();
        for (DishFlavor dishFlavor:dishFlavors){
            dishFlavor.setDishId(dishid);
        }
        dishFlavorService.saveBatch(dishFlavors);
    }

    @Override
    public DishDto getByIdWithFlavor(Long id) {
        //获取dish对象
        Dish dish = this.getById(id);
        //获取flavor数组
        //构造条件函数
        LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(DishFlavor::getDishId,id);
        List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);
        //封装
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish,dishDto);
        dishDto.setFlavors(dishFlavorList);

        return dishDto;
    }

    @Override
    //开启事务管理
    @Transactional
    public void updateWithFlavor(DishDto dishDto) {
        //修改dish
        this.saveOrUpdate(dishDto);

        //删除口味,获取到dishid，用条件删除
        //构造条件删除
        LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(dishFlavorLambdaQueryWrapper);

        //插入口味，给每个flavor对象插入dish的id
        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor dishFlavor:flavors){
            dishFlavor.setDishId(dishDto.getId());
        }
        dishFlavorService.saveBatch(flavors);
    }


}
